package service.impl.v2;

import java.util.List;
import java.util.concurrent.DelayQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import dao.v2.ApplyReturnVOMapper;
import dao.v2.MemberCartVOMapper;
import dao.v2.MessageVOMapper;
import dao.v2.OrderVOMapper;
import dao.v2.UorderBackVOMapper;
import dao.v2.UorderVOMapper;
import factory.PoolFactoryManager;
import model.FileVO;
import model.LogOrder;
import model.LogOrderBack;
import model.MemberVO;
import model.OrderGoodVO;
import model.OrderTimer;
import model.OrderVO;
import model.SeqVO;
import model.UorderCaseVO;
import model.UorderGoodVO;
import model.UorderVO;
import service.v2.CacheManagerService;
import service.v2.SplitService;
import service.v2.UorderService;
import util.MessageUtil;
import util.PropertieUtil;

@Service
public class UorderServiceImpl implements UorderService{
	
	@Autowired
	private SplitService splitService;
	
	@Autowired
	private UorderVOMapper dao;
	
	@Autowired
	private OrderVOMapper orderVOMapper;
	
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	
	@Autowired
	private ApplyReturnVOMapper applyReturnVOMapper;
	
	@Autowired
	private MessageVOMapper messageVOMapper;
	
	@Autowired
	private UorderBackVOMapper uorderBackVOMapper;
	
	@Autowired
	private CacheManagerService cacheManagerService;
	
	public List<UorderVO> getOrderList(UorderVO orderVO ) {
		return dao.getOrderList(orderVO);
	}

	public int getTotal(UorderVO orderVO) {
		return dao.getTotal(orderVO);
	}

	public UorderVO getOneOrderById(String order_id) {
		return dao.getOneOrderById(order_id);
	}

	public UorderVO getOrderDetails(String order_id) {
		return dao.getOrderDetails(order_id);
	}
	
	//订单列表更新时 检查定时器
	public void dealOrderTimer(String member_id) throws Exception {
		List<OrderTimer> timerList = 	dao.getOrderListTimer(member_id);
		if(timerList==null||timerList.size()==0){
			return;
		}
		
		String[] order_id_List = new  String[timerList.size()];
		for (int i = 0; i < timerList.size(); i++) {
			order_id_List[i]=timerList.get(i).getOrder_id();
		}
		
		List<OrderVO> orderList = orderVOMapper.getSimpleOrderByIdList(order_id_List);
		for (int i = 0; i < timerList.size(); i++) {
			OrderTimer Timer  = timerList.get(i);
			for (int j = 0; j < orderList.size(); j++) {
				//订单ID
				String order_id = orderList.get(j).getId();
				if(timerList.get(i).getOrder_id().equals(order_id)){
					OrderVO order = orderList.get(j);
					//检查未付款的订单
					if((order.getState().equals("1")||order.getState().equals("2"))&&Timer.getType().equals("4")){
						
						//还在走的定时器
						if(Timer.getOpen_yn().equals("Y")){
							//时间已到
							if(Timer.getNew_time().equals("false")){
								//修改订单状态
								UorderCalcelNoPay(order_id,Timer.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by());
							}
							
							//时间还没到让它继续飞翔
							else{
								
							}
						}
						//已经停止了的定时器
						else if(Timer.getOpen_yn().equals("N")){
							int count = orderVOMapper.delOrderTimer(Timer.getId());
							if(count>0){
								OrderTimer orderTime = new OrderTimer();
								orderTime.setOrder_id(order_id);
								orderTime.setCase_id(Timer.getCase_id());
								orderTime.setOpen_yn("Y");
								orderTime.setType("4");
								orderTime.setTime(Timer.getTime());
								memberCartVOMapper.addOrderTimer(orderTime);
							}
						}
					}//未付款订单 END
					
					//检查7天收货订单(包裹)
					if(order.getState().equals("4")){
						Timer.getCase_id();
					}
					
				}//处理结果 END
			}
		}
	}
		
	/**
	 * 未付款取消订单 已到时
	 */
	public void UorderCalcelNoPay(String order_id,String timer_id,String ticket_status,String pay_type,String create_by) throws Exception{
				OrderTimer timer = dao.getCaseOverTimerByIdAndType(timer_id,"4");
				if(timer!=null){
					int count = orderVOMapper.updOrderState(order_id,"6","1");
					if(count>0){
						System.out.println("时间到取消订单***********************");
						//修改包裹状态为 交易失败
						dao.updOrderCaseNoPay(order_id);
						//删除定时器
						orderVOMapper.delOrderTimer(timer_id);
						//查询该订单中存在的商品
						List<OrderGoodVO> orderGoodList	= orderVOMapper.getOrderGoodByOrderId(order_id);
						//返还库存
						for (int j = 0; j < orderGoodList.size(); j++) {
							int updCount = orderVOMapper.updGoodLimitNum(order_id,orderGoodList.get(j).getGood_id(),orderGoodList.get(j).getNum());
							if(updCount==0){
								orderVOMapper.updStandardNum(orderGoodList.get(j).getGood_standard_id(),orderGoodList.get(j).getNum());	
							}else{
								//清除缓存
								cacheManagerService.deleteSpecialListCache();
								cacheManagerService.deleteGoodDetailCache(CacheManagerServiceImpl.good_detail_key+orderGoodList.get(j).getGood_id());	
							}
						}
						OrderVO order = orderVOMapper.getOrderById(order_id);
						LogOrder log_ord = new LogOrder();
						log_ord.setOrder_id(order_id);
						log_ord.setMember_id(create_by);
						if("1".equals(order.getCountry())){
							log_ord.setRemark("【订单】申请取消订单");
						}else if("0".equals(order.getCountry())){
							log_ord.setRemark("【Order】 Your order has been submit,and is in process.");
						}
						//log_ord.setType("7");
						orderVOMapper.InsertLogOrder(log_ord);
						
						if("1".equals(ticket_status)){
								splitService.payBackUseTicket(order_id,pay_type,create_by,null,null);
						}
					}
				}
	}
	
	/**
	 * 未付款取消订单 已到时 手动
	 */
	public void UorderCalcelNoPayBySelf(String order_id,String timer_id,String ticket_status,String pay_type,String create_by) throws Exception{
		
			int count = orderVOMapper.updOrderState(order_id,"6","1");
			if(count>0){
				System.out.println("时间到取消订单***********************");
				//修改包裹状态为 交易失败
				dao.updOrderCaseNoPay(order_id);
				//删除定时器
				orderVOMapper.delOrderTimer(timer_id);
				//查询该订单中存在的商品
				List<OrderGoodVO> orderGoodList	= orderVOMapper.getOrderGoodByOrderId(order_id);
				//返还库存
				for (OrderGoodVO orderGood: orderGoodList) {
					int updCount = orderVOMapper.updGoodLimitNum(order_id,orderGood.getGood_id(),orderGood.getNum());
					if(updCount==0){
						orderVOMapper.updStandardNum(orderGood.getGood_standard_id(),orderGood.getNum());	
					}else{
						//清除缓存
						cacheManagerService.deleteSpecialListCache();
						cacheManagerService.deleteGoodDetailCache(CacheManagerServiceImpl.good_detail_key+orderGood.getGood_id());	
					}
				}
				
				OrderVO order = orderVOMapper.getOrderById(order_id);
				LogOrder log_ord = new LogOrder();
				log_ord.setOrder_id(order_id);
				log_ord.setMember_id(create_by);
				if("1".equals(order.getCountry())){
					log_ord.setRemark("【订单】申请取消订单");
				}else if("0".equals(order.getCountry())){
					log_ord.setRemark("【Order】 Your order has been submit,and is in process.");
				}
				//log_ord.setType("7");
				orderVOMapper.InsertLogOrder(log_ord);
				
				if("1".equals(ticket_status)){
					splitService.payBackUseTicket(order_id,pay_type,create_by,null,null);
				}
			}
	}
	
	public UorderCaseVO getOrderCaseById(String case_id) {
		return dao.getOrderCaseById(case_id);
	}

	public void cancelPaidOrder(String order_id, String case_id, String cancel_reason,String member_id,UorderCaseVO orderCase) {
		//修改包裹状态  并 update 取消理由
		dao.updOrderCaseStateByCaseId(orderCase.getId(),cancel_reason);
		//存log
		LogOrder log_ord = new LogOrder();
		log_ord.setOrder_id(order_id);
		log_ord.setMember_id(member_id);
		log_ord.setCase_id(case_id);
		UorderVO order = dao.getOneOrderById(order_id);
		String msg = "";
		if("1".equals(order.getCountry())){
			msg = "【订单】" + "包裹("+ orderCase.getCase_no()+")"+"已提交申请，正在受理";
		}else if("0".equals(order.getCountry())){
			msg = "【Order】Your order has been submit, and is in process.";
		}
		log_ord.setRemark(msg);
		log_ord.setType("7");
		orderVOMapper.InsertLogOrder(log_ord);
		
	}

	public List<LogOrder> getCancelCaseLog(String case_id) {
		return dao.getCancelCaseLog(case_id);
	}

	/**
	 * 确认收货
	 */
	public boolean caseConfirm(UorderCaseVO orderCase) {
		//包裹从 待收货 变为 交易成功
		int caseCount = dao.updOrderCaseState(orderCase.getId(), "4", "5");
		if(caseCount==0){
			return false;
		}
		//修改时间
		dao.getCaseRecieveTime(orderCase.getId());
		//删除定时器
		dao.delTimerByCaseIdAndType(orderCase.getId(),"1");
		//加销量
		List<UorderGoodVO> orderGoodList = dao.getOrderGoodByCaseId(orderCase.getId());
		for (UorderGoodVO orderGood :orderGoodList) {
			 orderVOMapper.updateStoreSellNum(orderGood.getGood_id(),orderGood.getNum());
		}
		int orderCount = dao.updOrderStateWhenConfirm(orderCase.getOrder_id());
		return orderCount==0?false:true;
	}

	public List<UorderGoodVO> getCaseEvaluate(String case_id) {
		return dao.getCaseEvaluate(case_id);
	}

	/**
	 * 提交包裹评价
	 * @throws Exception 
	 */
	public List<UorderGoodVO> subCaseEvaluate(String case_id, String order_good_id, String text, String imgs,String member_id) throws Exception {
		String folder_id = "";
		if(imgs!=null&&imgs!=""){
			SeqVO seq = new SeqVO();
			applyReturnVOMapper.getSeq(seq);
			folder_id = seq.getSeq();
			String[] filePah = imgs.split(",");
			for (int i = 0; i < filePah.length; i++) {
				FileVO fileVO = new FileVO();
				//评价图
				fileVO.setCat_id(PropertieUtil.loadPropertie("order_evalu_img"));
				fileVO.setPath(filePah[i]);
				fileVO.setFolder_id(folder_id);
				applyReturnVOMapper.addFile(fileVO);
			}
		}
		UorderGoodVO orderGood = new UorderGoodVO();
		orderGood.setId(order_good_id);
		orderGood.setEvaluate(text);
		orderGood.setMember_id(member_id);
		if(!"".equals(folder_id)){
			orderGood.setFold_id(folder_id);	
		}
		//评价
		dao.updOrderGoodEvaluate(orderGood);
		//check  包裹 评价
		dao.checkOrderEvaluate(case_id);
		dao.checkTotalEvaluate(case_id);
		List<UorderGoodVO> orderGoodList = dao.getCaseEvaluateAfterSub(order_good_id,case_id);
		return orderGoodList;
	}
	
	//处理定时器
	public void dealPersonTimer(String member_id) throws Exception{
		//获取个人订单中 所有已过期 Timer
		List<OrderTimer> timerList = dao.getOverDueTimer(member_id);
		UorderVO order = null;
		UorderCaseVO orderCase = null;
		OrderTimer orderTime = null;
		for (OrderTimer timer :timerList) {
			// 4 一小时未付款   1  7天收货
			switch(timer.getType()){
			case "4":
				if("N".equals(timer.getOpen_yn())){
					int count = orderVOMapper.delOrderTimer(timer.getId());
					if(count>0){
						order = dao.getOneOrderById(timer.getOrder_id());
						orderTime = new OrderTimer();
						orderTime.setOrder_id(timer.getOrder_id());
						orderTime.setCase_id(timer.getCase_id());
						orderTime.setOpen_yn("Y");
						orderTime.setType("4");
						orderTime.setTime(timer.getTime());
						memberCartVOMapper.addOrderTimer(orderTime);
						autoCancelOrder(timer.getOrder_id(),orderTime.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by(),timer.getTime());
					}
				}else if("Y".equals(timer.getOpen_yn())){
					order = dao.getOneOrderById(timer.getOrder_id());
					UorderCalcelNoPay(order.getId(),timer.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by());
				}
				break;
			case "1":
				orderCase  = dao.getOrderCaseById(timer.getCase_id());
				//确认收货方法
				boolean state = caseConfirm(orderCase);
				if(state){
					order = dao.getOneOrderById(timer.getOrder_id());
					int orderBackCount = orderVOMapper.checkOrderBackState(orderCase.getOrder_id());
					
					//收货以后分润
					final String ticket_status = order.getTicket_status();
					final String order_type = order.getOrder_type();
					final String order_id = order.getId();
					PoolFactoryManager.newInstance().addExecuteTask(new Runnable() {
						
						@Override
						public void run() {
							conFirmOrderShareBenifit(orderBackCount,ticket_status,order_type,order_id);
						}
					});
					
				}
				break;
			}
		}
		
	}//处理定时器 end
	
	
	//确认收货分润
	public void conFirmOrderShareBenifit(int orderBackCount,String ticket_status,String order_type,String order_id){
			if("0".equals(ticket_status)&&"0".equals(order_type)){
				//判断订单是否退过
				if(orderBackCount==0){
					try {
						splitService.settleAward(order_id);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		
			else if("1".equals(ticket_status)&&"0".equals(order_type)){
				// 提货券售出日志状态更变结算
				try {
					if(orderBackCount==0){
						splitService.updateTicketLogSellSuccess(order_id);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
	}
	/**
	 * 交易成功(包裹)
	 */
	public UorderVO getConfirmMsg(String case_id) {
		return dao.getConfirmMsg(case_id);
	}

	/**
	 * 后台处理定时器
	 * @throws Exception 
	 */
	public void dealPersonTimerBackOfiice() throws Exception{
		List<OrderTimer> timerList = dao.getOverDueTimer(null);
		for (int i = 0; i < timerList.size(); i++) {
			OrderTimer timer = timerList.get(i);
			//一小时未付款 N的时间大于一天
			if("4".equals(timer.getType())&&"N".equals(timer.getOpen_yn())&&Integer.parseInt(timer.getOver_time())>24*3600){
				/*UorderVO order = dao.getOneOrderById(timer.getOrder_id());
				UorderCalcelNoPay(order.getId(),timer.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by());*/
				dao.updOrderTimerOpenYn(timer.getId(), "Y");
			}
			//一小时未付款 Y
			if("4".equals(timer.getType())&&"Y".equals(timer.getOpen_yn())){
				UorderVO order = dao.getOneOrderById(timer.getOrder_id());
				UorderCalcelNoPay(order.getId(),timer.getId(),order.getTicket_status(),order.getPay_type(),order.getCreate_by());
			}
			
			//7天收货
			if("1".equals(timer.getType())){
				UorderCaseVO orderCase  = dao.getOrderCaseById(timer.getCase_id());
				if(orderCase!=null){
					//确认收货方法
					boolean state = caseConfirm(orderCase);
					if(state){
						UorderVO order = dao.getOneOrderById(timer.getOrder_id());
						int orderBackCount = orderVOMapper.checkOrderBackState(orderCase.getOrder_id());
						conFirmOrderShareBenifit(orderBackCount,order.getTicket_status(),order.getOrder_type(),order.getId());
					}	
				}
			}
			//14天未收到退货商品
			if("2".equals(timer.getType())){
				//取消orderback 
				if(timer.getOrder_back_id()!=null&&!"".equals(timer.getOrder_back_id())){
					int count = orderVOMapper.delOrderTimer(timer.getId());
					if(count>0){
						UorderVO order = dao.getOneOrderById(timer.getOrder_id());
						
						
						applyReturnVOMapper.updOrderBackState(timer.getOrder_back_id(),"9");
						LogOrderBack log = new LogOrderBack();
						log.setOrder_back_id(timer.getOrder_back_id());
						log.setMember_id(timer.getMember_id());
						log.setRemark("因未在14天内收到寄回商品,已取消退货申请");
						if("0".equals(order.getCountry())){
							log.setRemark("As we haven’t received your returned goods within 14 days, your return application has been cancelled.");
						}else{
							log.setRemark("因未在14天内收到寄回商品,已取消退货申请");
						}
						log.setType("0");
						applyReturnVOMapper.addLogOrderBack(log);
						
						int backCount  = uorderBackVOMapper.getBackProcessCount(timer.getOrder_back_id());
						if(backCount==0){
							
							int updCount = dao.updOrderCaseState(timer.getCase_id(), "7", "4");
							if(updCount>0){
								OrderTimer order_time = dao.getTimerOrderByCaseId(timer.getCase_id(), "1");
								
								dao.delTimerByCaseIdAndType(timer.getCase_id(), "1");
								OrderTimer orderTime = new OrderTimer();
								orderTime.setOrder_id(timer.getOrder_id());
								orderTime.setCase_id(timer.getCase_id());
								orderTime.setOpen_yn("Y");
								orderTime.setType("1");
								orderTime.setTime(order_time.getTime());
								memberCartVOMapper.addOrderTimer(orderTime);
							}
						}
					}
					
				}
			}
		}
	}
	
	//延时队列
		public void autoCancelOrder(String order_id,String order_timer_id,String ticket_status,String pay_type,String create_by,String pay_timer) throws Exception{
			
			DelayQueue<MessageUtil> queue = new DelayQueue<MessageUtil>();  
			long time = Long.parseLong(pay_timer.toString())*1000;
			MessageUtil m1 = new MessageUtil("test333", time);
			queue.offer(m1);
			
			new Thread(new Runnable() {
				public void run() {
					try{
						MessageUtil take = queue.take();
						UorderCalcelNoPay(order_id, order_timer_id, ticket_status, pay_type, create_by);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}).start();
		}

		
		public List<UorderVO> getDeliverAssist(String member_id) {
			messageVOMapper.resetMemberMsg(member_id, "3");
			return dao.getDeliverAssist(member_id);
		}

		public List<UorderVO> getCaseCount(String member_id,String lang) {
			return dao.getCaseCount(member_id,lang);
		}
}
